﻿@using Rj.PersonnelVerification.Client.Server
@using System.IdentityModel.Tokens.Jwt
@inherits LayoutComponentBase
@inject IJSRuntime js
<MudThemeProvider/>
<MudDialogProvider/>
<MudSnackbarProvider/>

<MudLayout>
    <MudAppBar Elevation="1">
        <MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit" Edge="Edge.Start" OnClick="@DrawerToggle" />
        <MudText Typo="Typo.h5" Class="ml-3">人证核查</MudText>
        <MudSpacer />
        <MudIconButton Icon="@Icons.Material.Filled.MoreVert" Color="Color.Inherit" Edge="Edge.End" />
    </MudAppBar>
    <MudDrawer @bind-Open="_drawerOpen" ClipMode="DrawerClipMode.Always" Elevation="2">
        <MudNavMenu>
            <MudNavLink Href="/" Icon="@Icons.Material.Filled.Dashboard" Match="NavLinkMatch.All">主页</MudNavLink>
            <MudNavGroup Title="人证核查" Icon="@Icons.Material.Filled.Storage" Expanded="true">
                <MudNavLink Href="/VerficaManage" Icon="fas fa-user-shield" Match="NavLinkMatch.Prefix">人证补传</MudNavLink>
            </MudNavGroup>
            <MudNavLink Href="/about" Icon="@Icons.Material.Filled.Science" Match="NavLinkMatch.Prefix">关于</MudNavLink>
        </MudNavMenu>
    </MudDrawer>
    <MudMainContent> 
        @Body
    </MudMainContent> 
</MudLayout>

@code {
    [Inject] CustomAuthStateProvider AuthStateProvider { get; set; }
    [Inject] NavigationManager Navigation { get; set; }
    bool _drawerOpen = true;
    private async Task Logout()
    {
        await js.InvokeVoidAsync("localStorage.removeItem", "authToken");
        AuthStateProvider.MarkUserAsLoggedOut();
        Navigation.NavigateTo("/login");
    }

    void DrawerToggle()
    {
        _drawerOpen = !_drawerOpen;
    }

    protected override async Task OnInitializedAsync()
    {
        // 从 localStorage 获取 token
        var token = await js.InvokeAsync<string>("localStorage.getItem", "authToken");

        if (!string.IsNullOrEmpty(token))
        {
            // 解析 token 并检查是否过期
            var isExpired = IsTokenExpired(token);

            if (isExpired)
            {
                Console.WriteLine("Token 已过期，跳转到登录页面。");
                // 执行过期处理，例如跳转到登录页面
                Navigation.NavigateTo("/login");
            }
            else
            {
                Console.WriteLine("Token 有效。");
            }
        }
    }

    public bool IsTokenExpired(string token)
    {
        var jwtHandler = new JwtSecurityTokenHandler();
        if (jwtHandler.CanReadToken(token))
        {
            var jwtToken = jwtHandler.ReadJwtToken(token);

            var expirationClaim = jwtToken.Claims.FirstOrDefault(c => c.Type == "exp")?.Value;
            if (expirationClaim != null && long.TryParse(expirationClaim, out var exp))
            {
                var expirationTime = DateTimeOffset.FromUnixTimeSeconds(exp).UtcDateTime;

                return expirationTime.Day != DateTime.UtcNow.Day;
            }
        }
        return true;
    }
}